﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Resto.CostControl.Core.Models.SysSettings;
using QuickApp.Core;
using System.Web.Script.Serialization;
using System.Text;
using QuickApp.MVCControl.Tree;
using System.Web.Security;
using QuickApp.MVCControl.Form;

namespace Resto.CostControl.Web.Controllers
{
    public class HomeController : Controller
    {
        #region 登陆相关Action
        public ActionResult Login(string ReturnUrl)
        {
            if (string.IsNullOrEmpty(ReturnUrl))
            {
                ViewData["RedirectUrl"] = Url.Action("Index");
            }
            else
            {
                ViewData["RedirectUrl"] = ReturnUrl;
            }
            return View();
        }

        public ActionResult Logout()
        {
            Session.Abandon();
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }

        [HttpPost]
        public JsonResult Login(FormCollection form)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                string userCode = form["UserID"];
                string pwd = form["Password"];

                UserInfo user = userRepo.Find(u => u.UserCode == userCode);
                if (user == null)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "用户名或密码错误";
                }
                else
                {
                    //if (user.Password == FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5"))
                    //{
                    FormsAuthentication.SetAuthCookie(userCode, false);
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                    //}
                }
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "登录失败：" + ex.Message;
            }
            return Json(msg);
        }

        [Ninject.Inject]
        public IRepository<UserInfo> userRepo { get; set; }
        #endregion

        #region 首页及左边菜单数据
        public ActionResult Index()
        {
            //ViewBag.UserName = nbUserContext.Current.CurrentUser.UserName;
            //ViewBag.UserId = nbUserContext.Current.CurrentUser.UserId;

            return View();
        }

        //[xEasyAppAuthorize()]
        public JavaScriptResult Menu()
        {
            List<Privilege> menus = privilegeRepo.FindAll(p => p.PrivilegeType == "Menu").OrderBy(x => x.SeqNo).ToList();
            List<string> usermenuids = new List<string>();//_SysManageService.GetUserMenuIds(base.UserId);

            List<Privilege> topmenus = menus.FindAll(x => string.IsNullOrEmpty(x.ParentId));
            List<JsonTreeNode> list = BuildTreeNode(menus, topmenus, usermenuids);

            JavaScriptSerializer s = new JavaScriptSerializer();
            StringBuilder sb = new StringBuilder();
            s.Serialize(list, sb);
            sb.Insert(0, "var menudata=");
            return JavaScript(sb.ToString());
        }

        private List<JsonTreeNode> BuildTreeNode(List<Privilege> allmenus, List<Privilege> menus, List<string> usermenuids)
        {
            List<JsonTreeNode> treenodelist = new List<JsonTreeNode>();
            bool isSupperAdmin = true;// base.IsInRole(AppConfig.SuperAdminRoleCode);
            foreach (Privilege p in menus)
            {
                if (isSupperAdmin || usermenuids.Contains(p.PrivilegeCode))
                {
                    JsonTreeNode treenode = new JsonTreeNode();
                    treenode.id = p.PrivilegeCode;
                    treenode.text = p.PrivilegeName;

                    treenode.value = GetTruePath(p.Uri);
                    treenode.isexpand = false;
                    treenode.showcheck = false;
                    treenode.complete = true;
                    List<Privilege> cmenus = allmenus.FindAll(x => x.ParentId == p.Id);
                    if (cmenus != null && cmenus.Count > 0)
                    {
                        treenode.ChildNodes.AddRange(BuildTreeNode(allmenus, cmenus, usermenuids));

                        if (treenode.ChildNodes.Count > 0)
                        {
                            if ((p.PrivilegeName != "基础数据") && (p.PrivilegeName != "系统设置"))
                            {
                                treenode.isexpand = true;
                            }
                            treenode.hasChildren = true;
                        }
                    }
                    treenodelist.Add(treenode);
                }

            }
            return treenodelist;
        }

        private string GetTruePath(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                if (path.ToLower().StartsWith("http://") || path.ToLower().StartsWith("https://"))
                {
                    return path;
                }
                if (path.StartsWith("~/"))
                {
                    return Url.Content(path);

                }
                return path;
            }
            return "";
        }

        [Ninject.Inject]
        public IRepository<Privilege> privilegeRepo { get; set; }
        #endregion

        #region portal
        //
        // GET: /Home/Portal

        public ActionResult Portal()
        {
            return View();
        }
        #endregion
    }
}
